package com.wakyde.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @Description: TODO
 * @author: wakyde
 * @date: 2022年05月09日 16:10
 */
public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 要获取下载文件的路径
        String filePath = "C:\\Users\\john\\Desktop\\扫码填写简历.jpg";
        // 下载的文件名是啥?
        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
//        System.out.println(fileName);
        // 设置想办法让浏览器支持下载我们需要的东西 中文文件名URLEncoder.encode编码,否则可能乱码
        resp.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
        // 获取下载文件的输入流
        FileInputStream in = new FileInputStream(filePath);
        // 创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        // 获取OutputStream对象
        ServletOutputStream out = resp.getOutputStream();
        // 将FileOutputStream流写入到buffer缓冲区  使用OutputStream将缓冲区中的数据输出到客户端
        while ((len=in.read(buffer)) > 0){
            out.write(buffer, 0, len);
        }

        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }
}
